'use client'

import Todo from "@/components/Todo";
import axios from "axios";
import { Button } from "flowbite-react";
import { useEffect, useState } from "react";
import { ToastContainer, toast } from "react-toastify";
import 'react-toastify/dist/ReactToastify.css';

export default function Home() {

  const [loading, setLoading] = useState(false);

  const [formData, setFormData] = useState({ title: '', description: '' });

  const [todos, setTodos] = useState([]);

  const fetchTodos = async () => {
    try {
      setLoading(true);
      const response = await axios.request({ method: 'GET', url: '/api' });
      setTodos(response.data.todos);
    }
    finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTodos();
  }, []);

  const onChangeHandler = (e) => {
    const name = e.target.name;
    const value = e.target.value;
    setFormData(form => ({ ...form, [name]: value }));
  };

  const onSubmitHandler = async (e) => {
    e.preventDefault();
    try {
      setLoading(true);
      const response = await axios.request({ method: 'POST', url: '/api', data: formData });
      toast.success(response.data.msg);
      setFormData({ title: '', description: '' });
    } catch (e) {
      toast.error('Error');
    } finally {
      setLoading(false);
      fetchTodos();
    }
  };

  const deleteTodo = async (id) => {
    try {
      setLoading(true);
      const response = await axios.request({ method: 'DELETE', url: '/api', params: { mongoId: id } });
      toast.success(response.data.msg);
    }
    finally {
      setLoading(false);
      fetchTodos();
    }
  };

  const finishTodo = async (id) => {
    try {
      setLoading(true);
      const response = await axios.request({ method: 'PUT', url: '/api', params: { mongoId: id } });
      toast.success(response.data.msg);
    }
    finally {
      setLoading(false);
      fetchTodos();
    }
  };

  return (
    <>
      <ToastContainer position="top-center" autoClose="2000" />

      <form onSubmit={e => onSubmitHandler(e)} className="flex item-start flex-col gap-2 w-[80%] max-w-[600px] mt-24 px-2 mx-auto">
        <input type="text" value={formData.title} onChange={e => onChangeHandler(e)} name="title" placeholder="Enter Title" className="px-3 py-2 border-2 w-full" />
        <textarea name="description" value={formData.description} onChange={e => onChangeHandler(e)} placeholder="Enter Description" className="px-3 py-2 border-2 w-full"></textarea>
        <Button type="submit" isProcessing={loading} className="bg-orange-600 py-3 px-l1 text-white">Add Todo</Button>
      </form>

      <div className="relative overflow-x-auto mt-24 w-[60%] mx-auto">
        <table className="w-full text-sm text-left rtl:text-right text-gray-500 dark:text-gray-400">
          <thead className="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">
            <tr>
              <th scope="col" className="px-6 py-3">
                Id
              </th>
              <th scope="col" className="px-6 py-3">
                Title
              </th>
              <th scope="col" className="px-6 py-3">
                Description
              </th>
              <th scope="col" className="px-6 py-3">
                Status
              </th>
              <th scope="col" className="px-6 py-3">
                Action
              </th>
            </tr>
          </thead>
          <tbody>
            {todos.map(todo => (
              <Todo todo={todo} key={todo._id} deleteTodo={() => deleteTodo(todo._id)} finishTodo={() => finishTodo(todo._id)} />
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}
